package com.cy.detectsys.util;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;

public class RSAUtil {

    /**
     * 使用公钥加密数据
     *
     * @param data       需要加密的数据
     * @param publicKey  公钥
     * @return 加密后的数据
     * @throws Exception 加密过程中的异常
     */
    public static byte[] encrypt(byte[] data, Key publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 使用私钥解密数据
     *
     * @param data       需要解密的数据
     * @param privateKey 私钥
     * @return 解密后的数据
     * @throws Exception 解密过程中的异常
     */
    public static byte[] decrypt(byte[] data, Key privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 从字符串中加载公钥
     *
     * @param publicKeyStr 公钥字符串
     * @return 公钥对象
     * @throws Exception 加载公钥时的异常
     */
    public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * 从字符串中加载私钥
     *
     * @param privateKeyStr 私钥字符串
     * @return 私钥对象
     * @throws Exception 加载私钥时的异常
     */
    public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyStr));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }
}